/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.basicdata.basictree.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.basicdata.basictree.entity.PartDevice;
import com.jeeplus.modules.basicdata.basictree.service.PartDeviceService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;


@RestController
@RequestMapping(value = "/basicdata/basictree/partDevice")
public class PartDeviceController extends BaseController {

	@Autowired
	private PartDeviceService partDeviceService;

	@ModelAttribute
	public PartDevice get(@RequestParam(required=false) String deviceId) {
		PartDevice entity = null;
		if (StringUtils.isNotBlank(deviceId)){
			entity = partDeviceService.get(deviceId);
		}
		if (entity == null){
			entity = new PartDevice();
		}
		return entity;
	}

	/**
	 * 设备节点信息列表数据
	 */
	@RequiresPermissions("basicdata:basictree:partDevice:list")
	@GetMapping("list")
	public AjaxJson list(PartDevice partDevice, HttpServletRequest request, HttpServletResponse response) {
		Page<PartDevice> page = partDeviceService.findPage(new Page<PartDevice>(request, response), partDevice);
		return AjaxJson.success().put("page",page);
	}
	/**
	 * 根据Id获取设备节点信息数据
	 */
	@RequiresPermissions(value={"basicdata:basictree:partDevice:view","basicdata:basictree:partDevice:add","basicdata:tree:partDevice:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(PartDevice partDevice) {
		return AjaxJson.success().put("partDevice", partDevice);
	}

	@RequiresPermissions(value={"user", "basicdata:basictree:partDevice:view","basicdata:basictree:partDevice:add","basicdata:tree:partDevice:edit"},logical=Logical.OR)
	@GetMapping("queryByFileCode")
	public PartDevice getByFileCode(String fileCode) {
		return partDeviceService.getByFileCode(fileCode);
	}

	/**
	 * 保存设备节点信息
	 */
	@RequiresPermissions(value={"basicdata:basictree:partDevice:add","basicdata:basictree:partDevice:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(PartDevice partDevice, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(partDevice);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		partDeviceService.save(partDevice);//保存
		return AjaxJson.success("保存设备节点信息成功");
	}


	/**
	 * 批量删除设备节点信息
	 */
	@RequiresPermissions("basicdata:basictree:partDevice:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			partDeviceService.delete(partDeviceService.get(id));
		}
		return AjaxJson.success("删除设备节点信息成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("basicdata:basictree:partDevice:export")
    @GetMapping("export")
    public AjaxJson exportFile(PartDevice partDevice, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "设备节点信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<PartDevice> page = partDeviceService.findPage(new Page<PartDevice>(request, response, -1), partDevice);
    		new ExportExcel("设备节点信息", PartDevice.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出设备节点信息记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("basicdata:basictree:partDevice:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<PartDevice> list = ei.getDataList(PartDevice.class);
			for (PartDevice partDevice : list){
				try{
					partDeviceService.save(partDevice);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条设备节点信息记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条设备节点信息记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入设备节点信息失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入设备节点信息数据模板
	 */
	@RequiresPermissions("basicdata:basictree:partDevice:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "设备节点信息数据导入模板.xlsx";
    		List<PartDevice> list = Lists.newArrayList();
    		new ExportExcel("设备节点信息数据", PartDevice.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 获取当前节点的所有下一级子节点
	 *
	 * @param id 父节点的id值
	 * @param extId
	 * @return
	 */
    @RequiresPermissions("user")
	@GetMapping("nextLevelTreeData")
	public AjaxJson nextLevelTreeData(@RequestParam(required = false)String id, @RequestParam(required = false) String extId) {
		List<PartDevice> nextLevelTreeData = nextLevelTree(id);
		return AjaxJson.success().put("data", nextLevelTreeData);
	}

	/**
	 *	取得从根节点到3层的树结构
	 * @return
	 */
	@RequiresPermissions("user")
	@GetMapping("getInitTreeData")
	public AjaxJson getInitTreeData() {
		List<PartDevice> oneLevel = nextLevelTree("0");
		for(PartDevice one : oneLevel) {
			List<PartDevice> twoPartDevices = nextLevelTree(one.getFileCode());
			one.setChildren(twoPartDevices);
		}
		List<PartDevice> initTreeData = oneLevel;
		return AjaxJson.success().put("data", initTreeData);
	}
	/**
	 * 获取下一层树数据
	 * @param fileCode 节点唯一标识
	 * @return
	 */
	private List<PartDevice> nextLevelTree(String fileCode) {
		// 根据id获取设备的层树
		String level = "0";
		if (fileCode != null && !"0".equals(fileCode)) {
			level = getLevelById(fileCode);
		} else {
			fileCode = "";
		}
		PartDevice partDevice = new PartDevice();
		partDevice.setFileCode(fileCode);
		partDevice.setFileLevel(Integer.parseInt(level) + 1 + "");
		List<PartDevice>  nextLevelTreeData = partDeviceService.getChildern(partDevice);
		return nextLevelTreeData;
	}

	/**
	 * 根据编码判断层数，避免从后台数据库读取
	 * @param fileCode 节点唯一标识
	 * @return
	 */
	private String getLevelById(String fileCode) {
		if (fileCode.length() == 2) {
			return "1";
		} else if (fileCode.length() == 5) {
			return "2";
		} else if (fileCode.length() == 9) {
			return "3";
		} else if (fileCode.length() == 12) {
			return "4";
		} else {
			return "5";
		}
	}
}